//
//  WBStatusDAL.swift
//  WeiBo
//
//  Created by 韩菲菲 on 16/8/22.
//  Copyright © 2016年 韩菲菲. All rights reserved.
//

import UIKit

class WBStatusDAL: NSObject {
    
    
    // MARK: - 清理缓存
    class func deleteCache(){
    
        let timeStr = NSDate.deleteSinaTime()
        
        //sql语句
        let sql = "DELETE FROM T_Status WHERE createtime<'\(timeStr)'"
        
        WBSQLManager.sharedManager.queue.inDatabase { (db) in
            
            
            if db.executeUpdate(sql, withArgumentsInArray: nil){
            
                print("删除数据成功")
            }else{
            
                print("删除数据失败")
            }
        }
    
    }
    
    
    
    // MARK: - 检查本地是否有缓存数据
    class func checkoutCache(since_id:Int64 ,max_id:Int64 , finish:(result:[[String:AnyObject]]?)->()){
        
        //获取缓存数据
        let result = getCache(since_id, max_id: max_id)
        
        if result?.count > 0{
            
            // 代表本地有数据
            finish(result: result)
            print("本地获取数据")
            
        }else
        {
            //网络获取数据
            print("网络请求数据")
            WBNetworkingTool.sharedTool.getHomeData(since_id, max_id: max_id, success: { (response) in
                
                guard let result = response?["statuses"] as? [[String:AnyObject]] else{
                    
                    finish(result: nil)
                    
                    return
                }
                
                //网络请求数据返回成功
                //保存到本地
                saveCache(result)
                
                finish(result: result)
                
                
                }, failure: { (error) in
                    
                    print("数据请求失败")
                    
                    finish(result: nil)
                    
            })
        }
        
    }
    
    
    // MARK: - 查询缓存数据
    class func getCache(since_id:Int64 ,max_id:Int64) -> [[String: AnyObject]]?{
        
        //用户id
        //取出用户id 如果不存在 直接返回
        guard let userid = WBUserAccountViewModel.sharedUserAccountViewModel.userAccount?.uid else{
            
            return nil
        }
        
        if since_id == 0 && max_id == 0{
        
            return nil
        }
        
        //准备sql语句
        var sql = ""
        sql += "SELECT * FROM T_Status\n"
        sql += "WHERE userid=\(userid)\n"
        
        //代表下拉刷新
        if since_id > 0{
            
            sql += "AND statusid>\(since_id)\n"
            
        }
        
        //代表上啦加载更多
        if max_id > 0{
            
            sql += "AND statusid<=\(max_id)\n"
            
        }
        //
        sql += "ORDER BY statusid DESC\n"
        sql += "LIMIT 20"
        
        let result = WBSQLManager.sharedManager.getResultArrayWithSQL(sql)
        
        //创建临时可变字典
        var tempArr:[[String:AnyObject]] = [[String:AnyObject]]()
        
        for dict in result{
            
            let data = dict["status"] as! NSData
            
            let dic = try! NSJSONSerialization.JSONObjectWithData(data, options: [])
            
            tempArr.append(dic as! [String:AnyObject])
        }
        
        return tempArr
        
    }
    
    
    
    // MARK: - 保存网络请求回来的数据
    class func saveCache(result: [[String:AnyObject]]){
        
        //取出用户id 如果不存在 直接返回
        guard let userid = WBUserAccountViewModel.sharedUserAccountViewModel.userAccount?.uid else{
            
            return
        }
        
        for dict in result{
            
            //获取微博id
            let statusid = dict["id"] as! NSNumber
            
            //把字典转换成二进制 因为dict就是微博字典
            let data = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
            
            //sql语句
            let sql = "INSERT OR REPLACE INTO T_Status (statusid,userid,status) VALUES (?,?,?)"
            
            //执行sql语句  事务操作 快 安全
            WBSQLManager.sharedManager.queue.inTransaction { (db, rollBack) in
                
                if db.executeUpdate(sql, withArgumentsInArray: [statusid,userid,data]){
                    
                    print("数据保存成功")
                }else{
                    
                    print("数据保存失败")
                    
                    //执行rollback
                    rollBack.memory = true
                    
                }
                
            }
            
        }
        
        
        
    }
    
}
